import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter_trip/dao/home_dao.dart';
import 'package:flutter_trip/model/grid_nav_model.dart';
import 'package:flutter_trip/model/home_model.dart';
import 'package:flutter_trip/model/sales_box_model.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/utils/http/http_utils.dart';
import 'package:flutter_trip/widget/grid_nav.dart';
import 'package:flutter_trip/widget/grid_nav2.dart';
import 'package:flutter_trip/widget/grid_nav3.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/local_nav.dart';
import 'package:flutter_trip/widget/local_nav2.dart';
import 'package:flutter_trip/widget/sales_box_nav.dart';
import 'package:flutter_trip/widget/search_bar.dart';
import 'package:flutter_trip/widget/sub_nav.dart';
import 'package:flutter_trip/widget/sub_nav2.dart';
import 'package:flutter_trip/widget/webview.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';

import '../model/common_model.dart';

//定义常量 当列表滚到超过100 appbar显示白色
const APPBAR_SCROLL_OFFSET = 100;
const SEARCH_BAR_DEFAULT_TEXT = '网红打卡地 景点 酒店 美食';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //banner集合
  final List _imageUrls = [
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F0F220092145%2F200F2092145-4-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652277037&t=fa69d760f749ed0531117fa49c3db7cf",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1111%2F05161Q64001%2F1P516164001-3-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652277037&t=2aaf7ff781fa06ffee2134bcd882fca5",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F1Z9291TIBZ6-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652277037&t=cc4a4a96f58150cbd054986a109bd8fc"
  ];

  //默认加载
  bool _loading = true;

  //Appbar渐变
  double appBarAlpha = 0;

  String resultString = "";

  //接口数据源
  List<CommonModel> bannerList = [];
  List<CommonModel> localNavList = [];
  List<CommonModel> subNavList = [];
  GridNavModel? gridNavModel;
  SalesBoxModel? salesBox;

  //滑动监听
  void _onScroll(offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  Future<Null> _handleRefresh() async {
    HttpUtils.get("home_page.json", (data) {
      HomeModel model = HomeModel.fromJson(data);
      setState(() {
        bannerList = model.bannerList;
        localNavList = model.localNavList;
        gridNavModel = model.gridNav;
        subNavList = model.subNavList;
        salesBox = model.salesBox;
        _loading = false;
      });
    }, errorCallback: (onError) {
      setState(() {
        _loading = false;
      });
    } );

    // try {
    //   HomeModel model = await HomeDao.fetch();
    //   setState(() {
    //     bannerList = model.bannerList;
    //     localNavList = model.localNavList;
    //     gridNavModel = model.gridNav;
    //     subNavList = model.subNavList;
    //     salesBox = model.salesBox;
    //     _loading = false;
    //   });
    // } catch (onError) {
    //   setState(() {
    //     _loading = false;
    //   });
    // }
    return null;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _handleRefresh();
    Future.delayed(Duration(milliseconds: 600), () {
      FlutterSplashScreen.hide();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfff2f2f2),
        body: LoadingContainer(
          isLoading: _loading,
          cover: false,
          child: Stack(
            children: [
              MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: RefreshIndicator(
                    onRefresh: _handleRefresh,
                    child: NotificationListener(
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollUpdateNotification &&
                            scrollNotification.depth == 0) {
                          //滚动且是列表滚动的时候
                          _onScroll(scrollNotification.metrics.pixels);
                        }
                        return false;
                      },
                      child: _listView,
                    ),
                  )),
              appBar,
            ],
          ),
        ));
  }

  //列表
  Widget get _listView {
    return ListView(
      children: [
        if (bannerList.isNotEmpty) banner,
        if (localNavList.isNotEmpty)
          Padding(
            padding: const EdgeInsets.fromLTRB(7, 4, 7, 4),
            child: LocalNav(localNavList: localNavList),
          ),
        if (gridNavModel != null)
          Padding(
            padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
            child: GridNav(gridNavModel: gridNavModel!),
          ),
        if (subNavList.isNotEmpty)
          Padding(
            padding: const EdgeInsets.fromLTRB(7, 4, 7, 4),
            child: SubNav(
              subNavList: subNavList,
            ),
          ),
        if (salesBox != null)
          Padding(
            padding: const EdgeInsets.fromLTRB(7, 4, 7, 4),
            child: SalesBox(
              salesBox: salesBox!,
            ),
          ),
      ],
    );
  }

  //轮播图View
  Widget get banner {
    return Container(
      height: 160,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => HiWebView(
                            url: bannerList[index].url,
                            statusBarColor: bannerList[index].statusBarColor,
                            hideAppBar: bannerList[index].hideAppBar,
                          )));
            },
            child: Image.network(
              bannerList[index].icon!,
              fit: BoxFit.fill,
            ),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  //appbar
//   Widget get _appBar => Opacity(
//         opacity: appBarAlpha,
//         child: Container(
//           height: 80,
//           decoration: BoxDecoration(color: Colors.white),
//           child: const Center(
//             child: Padding(
//               padding: EdgeInsets.only(top: 20),
//               child: Text("首页"),
//             ),
//           ),
//         ),
//       );
// }

  Widget get appBar {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
            colors: [Color(0x66000000), Colors.transparent],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          )),
          child: Container(
            height: 80,
            padding: EdgeInsets.only(top: 20),
            decoration: BoxDecoration(
                color:
                    Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255)),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {
              },
            ),
          ),
        )
      ],
    );
  }

  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              //AppBar渐变遮罩背景
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {
                Navigator.pop(context);
              },
            ),
          ),
        ),
        Container(
            height: appBarAlpha > 0.2 ? 0.5 : 0,
            decoration: const BoxDecoration(
                boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]))
      ],
    );
  }

  void _jumpToSearch() {
    Navigator.push(context, MaterialPageRoute(builder: (context)=>SearchPage(hideLeft: false ,)));
  }

  void _jumpToSpeak() {}
}
